package com.wfcm.controller;

import com.alibaba.fastjson.JSONObject;
import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import com.wfcm.entity.*;
import com.wfcm.exception.WFCMException;
import com.wfcm.service.*;
import com.wfcm.utils.*;
import com.wfcm.wxPay.MD5Util;
import com.wfcm.wxPay.ResponseHandler;
import com.wfcm.wxPay.WXOrderQuery;
import com.wfcm.wxPay.WXPayUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.runtime.directive.Foreach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/collage")
public class CollageController {
    private Logger log = LoggerFactory.getLogger(CollageController.class);

    @Autowired
    private WfGoodsOrderService goodsOrderService;
    @Autowired
    private WfCourseChapterService courseChapterService;
    @Autowired
    private WfCourseInfoService courseInfoService;
    @Autowired
    private WfVipCardService vipCardService;
    @Autowired
    private WfBillService billService;
    @Autowired
    private WfCollageActivityService collageActivityService;
    @Autowired
    private WfCollageOrderService collageOrderService;
    @Autowired
    private WfGoodsOrderRelationService goodsOrderRelationService;


    /**
     * 获取活动信息
     *
     * @return
     */
    @RequestMapping("getCollageActivity")
    @ResponseBody
    @IgnoreToken
    //@IgnoreSign
    public R getCollageActivity(HttpServletRequest req) {
        Integer activityId = Integer.valueOf(req.getParameter("activityId"));
        Map map = new HashMap();
        map.put("activityId", activityId);

        List<WfCollageActivityEntity> collageList = collageActivityService.queryList(map);
        if (collageList.size() > 0) {
            return R.ok().put("collage", collageList.get(0));
        }
        return R.ok();
    }

    /**
     * 判断是否新人
     *
     * @param
     * @return
     */
    @RequestMapping("isNew")
    @ResponseBody
    public R oldNew(HttpServletRequest req) {
        Integer uid = ISsoLoginHelper.confirm(req);//参团人id

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uid", uid);
        map.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.已过期）
        //获取已购课程个数
        List<WfGoodsOrderEntity> goodsOrderList = goodsOrderService.queryList(map);//根据uid获取订单
        if (goodsOrderList.size() > 0) {
            return R.ok().put("flag", 0);
        }
        return R.ok().put("flag", 1);//是新人
    }

    /**
     * 我的拼团列表
     *
     * @param
     * @return
     */
    @RequestMapping("myCollages")
    @ResponseBody

    public R myCollages(HttpServletRequest req) {
        String toUserId = String.valueOf(ISsoLoginHelper.confirm(req));//参团人id

        List<WfCollageOrderEntity> collageList = collageOrderService.queryListByToUserId(toUserId);

        return R.ok().put("collageList", collageList);
    }


    /**
     * 我的拼团
     *
     * @param
     * @return
     */
    @RequestMapping("myCollage")
    @ResponseBody
    public R myCollage(HttpServletRequest req) {
        int toUserId = ISsoLoginHelper.confirm(req);//参团人id
        String activityId = req.getParameter("activityId");
        String userId = req.getParameter("userId");//团长
        boolean isNew = "1".equals(req.getParameter("isNew")) ? true : false;//是否新人

        //判断是否已参加
        Map map = new HashMap<String, Object>();
        map.put("toUserId", toUserId);
        map.put("activityId", activityId);
        //获取状态status！=1 的最新订单
        WfCollageOrderEntity collage = collageOrderService.queryMyCollage(map);//获取团单状态；所买课程信息；参团最多人数；

        R r = new R();
        if (StringUtils.isBlank(userId)) {//没有发团人ID
            if (collage != null) {//
                int access = -1;
                access =  checkCourse(toUserId, collage.getForeignid());
                if (access > 0) {
                    return this.resultCollage(activityId,collage);//拼团结果
                    //return R.error(58, "此课程您已经购买！");
                }

                Map map1 = new HashMap<String, Object>();
                map1.put("userId", collage.getUserid());
                map1.put("activityId", activityId);
                map1.put("collageOrder", collage.getCollageorder());//获取最新拼团的参团人员信息
                List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

                Map map2 = new HashMap<String, Object>();
                map2.put("userId", collage.getUserid());
                map2.put("activityId", activityId);
                map2.put("collageOrder", collage.getCollageorder());
                int total = collageOrderService.queryTotal(map2);

                //拼团结果
                r.put("collage", collage);
                r.put("partners", collageList);
                r.put("total", total);
                r.put("page", 3);
                return r;
            } else {
                //我要开团
                Map toCallageMap = new HashMap();
                toCallageMap.put("activityId", activityId);
                List<WfCollageActivityEntity> collageList = collageActivityService.queryList(toCallageMap);
                WfCollageActivityEntity collageActivity = collageList.get(0);

                r.put("page", 1);
                r.put("collageActivity", collageActivity);
                return r;
            }
        } else {//有发团人ID
            //获取团长订单 状态status！=1 的最新订单
            //判断是否已参加
            Map map3 = new HashMap<String, Object>();
            map3.put("userId", userId);
            map3.put("activityId", activityId);
            WfCollageOrderEntity leaderCollage = collageOrderService.queryLeaderCollage(map3);//获取团单状态；所买课程信息；参团最多人数；

            if (collage != null) {//已参加
                int access = -1;
                access =  checkCourse(toUserId, collage.getForeignid());
                if (access > 0) {
                    return this.resultCollage(activityId,collage);//拼团结果
                    //return R.error(58, "此课程您已经购买！");
                }
                if (new Date().compareTo(collage.getEndtime()) > 0) {//如果本人最新拼团已过期，进入参团页面
                    if (isNew) {//新人
                        if(new Date().compareTo(leaderCollage.getEndtime()) > 0 || leaderCollage.getStatus() == 3){//如果邀请人的拼团也过期，查看自己的拼团信息
                            return this.resultCollage(activityId,collage);//拼团结果
                        }else{//邀请人的拼团没过期，进入参团页面
                            return this.addCollage(userId,activityId,leaderCollage);//参团
                        }
                    } else {//老人进邀请链接，只能开团
                        return this.toCollage(activityId);//开团
                    }
                } else {//如果本人的拼团未过期，查看用户自己的结果页
                    return this.resultCollage(activityId,collage);//拼团结果
                }
            } else {//没有参加
                if (isNew) {//新人
                    if (new Date().compareTo(leaderCollage.getEndtime()) > 0 || leaderCollage.getStatus()==3) {//如果邀请人最新拼团已过期，进入结果页面
                        return this.resultCollage(activityId,leaderCollage);//拼团结果
                    } else {//如果邀请人最新拼团进行中，进入参团页面
                        return this.addCollage(userId,activityId,leaderCollage);//参团
                    }
                } else {//老人进邀请链接，只能开团
                    return this.toCollage(activityId);//开团
                }
            }
        }
    }


    //参团
    public R addCollage(String userId,String activityId,WfCollageOrderEntity leaderCollage){

        R r = new R();
        //我要参团
        Map map1 = new HashMap<String, Object>();
        map1.put("userId", userId);
        map1.put("activityId", activityId);
        map1.put("collageOrder", leaderCollage.getCollageorder());//获取最新拼团的参团人员信息
        List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

        Map map2 = new HashMap<String, Object>();
        map2.put("userId", userId);
        map2.put("activityId", activityId);
        map2.put("collageOrder", leaderCollage.getCollageorder());
        int total = collageOrderService.queryTotal(map2);

        //拼团结果
        r.put("page", 2);//参团页
        r.put("collage", leaderCollage);
        r.put("partners", collageList);
        r.put("total", total);
        return r;
    }

    //拼团结果
    public R resultCollage(String activityId,WfCollageOrderEntity leaderCollage){

        R r = new R();
        Map map1 = new HashMap<String, Object>();
        map1.put("userId", leaderCollage.getUserid());
        map1.put("activityId", activityId);
        map1.put("collageOrder", leaderCollage.getCollageorder());//获取最新拼团的参团人员信息
        List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

        Map map2 = new HashMap<String, Object>();
        map2.put("userId", leaderCollage.getUserid());
        map2.put("activityId", activityId);
        map2.put("collageOrder", leaderCollage.getCollageorder());
        int total = collageOrderService.queryTotal(map2);

        //拼团结果
        r.put("page", 3);
        r.put("collage", leaderCollage);
        r.put("partners", collageList);
        r.put("total", total);
        return r;
    }

    //开团
    public R toCollage(String activityId){

        R r = new R();
        //我要开团
        Map toCallageMap = new HashMap();
        toCallageMap.put("activityId", activityId);
        List<WfCollageActivityEntity> collageList = collageActivityService.queryList(toCallageMap);
        WfCollageActivityEntity collageActivity = collageList.get(0);
        r.put("page", 1);//开团页
        r.put("collageActivity", collageActivity);
        return r;
    }


    /**
     * 我的拼团(已替代)
     *
     * @param
     * @return
     */
    @RequestMapping("myCollage2")
    @ResponseBody
    public R myCollage2(HttpServletRequest req) {
        int toUserId = ISsoLoginHelper.confirm(req);//参团人id
        String activityId = req.getParameter("activityId");
        String userId = req.getParameter("userId");//团长
        boolean isNew = "1".equals(req.getParameter("isNew")) ? true : false;//是否新人

        //判断是否已参加
        Map map = new HashMap<String, Object>();
        map.put("toUserId", toUserId);
        map.put("activityId", activityId);
        //获取状态status！=1 的最新订单
        WfCollageOrderEntity collage = collageOrderService.queryMyCollage(map);//获取团单状态；所买课程信息；参团最多人数；

        R r = new R();
        if (StringUtils.isBlank(userId)) {//没有发团人ID
            if (collage != null) {//
                Map map1 = new HashMap<String, Object>();
                map1.put("userId", collage.getUserid());
                map1.put("activityId", activityId);
                map1.put("collageOrder", collage.getCollageorder());//获取最新拼团的参团人员信息
                List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

                Map map2 = new HashMap<String, Object>();
                map2.put("userId", collage.getUserid());
                map2.put("activityId", activityId);
                map2.put("collageOrder", collage.getCollageorder());
                int total = collageOrderService.queryTotal(map2);

                //拼团结果
                r.put("collage", collage);
                r.put("partners", collageList);
                r.put("total", total);
                r.put("page", 3);
                return r;
            } else {
                //我要开团
                Map toCallageMap = new HashMap();
                toCallageMap.put("activityId", activityId);
                List<WfCollageActivityEntity> collageList = collageActivityService.queryList(toCallageMap);
                WfCollageActivityEntity collageActivity = collageList.get(0);

                r.put("page", 1);
                r.put("collageActivity", collageActivity);
                return r;
            }
        } else {//有发团人ID
            //获取团长订单 状态status！=1 的最新订单
            //判断是否已参加
            Map map3 = new HashMap<String, Object>();
            map3.put("userId", userId);
            map3.put("activityId", activityId);
            WfCollageOrderEntity leaderCollage = collageOrderService.queryLeaderCollage(map3);//获取团单状态；所买课程信息；参团最多人数；

            if (collage != null) {//已参加
                if (new Date().compareTo(collage.getEndtime()) > 0) {//如果本人最新拼团已过期，进入参团页面
                    if (isNew) {//新人
                        //我要参团
                        Map map1 = new HashMap<String, Object>();
                        map1.put("userId", userId);
                        map1.put("activityId", activityId);
                        map1.put("collageOrder", leaderCollage.getCollageorder());//获取最新拼团的参团人员信息
                        List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

                        Map map2 = new HashMap<String, Object>();
                        map2.put("userId", userId);
                        map2.put("activityId", activityId);
                        map2.put("collageOrder", leaderCollage.getCollageorder());
                        int total = collageOrderService.queryTotal(map2);

                        //拼团结果
                        r.put("page", 2);//参团页
                        r.put("collage", leaderCollage);
                        r.put("partners", collageList);
                        r.put("total", total);
                        return r;
                    } else {//老人进邀请链接，只能开团
                        //我要开团
                        Map toCallageMap = new HashMap();
                        toCallageMap.put("activityId", activityId);
                        List<WfCollageActivityEntity> collageList = collageActivityService.queryList(toCallageMap);
                        WfCollageActivityEntity collageActivity = collageList.get(0);
                        r.put("page", 1);//开团页
                        r.put("collageActivity", collageActivity);
                        return r;
                    }
                } else {//邀请人最新拼团进行中
                    if (userId.equals(String.valueOf(toUserId))) {//如果邀请人是本人，查看结果页面

                        Map map1 = new HashMap<String, Object>();
                        map1.put("userId", userId);
                        map1.put("activityId", activityId);
                        map1.put("collageOrder", leaderCollage.getCollageorder());//获取最新拼团的参团人员信息
                        List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

                        Map map2 = new HashMap<String, Object>();
                        map2.put("userId", userId);
                        map2.put("activityId", activityId);
                        map2.put("collageOrder", leaderCollage.getCollageorder());
                        int total = collageOrderService.queryTotal(map2);

                        //拼团结果
                        r.put("page", 3);
                        r.put("collage", leaderCollage);
                        r.put("partners", collageList);
                        r.put("total", total);
                        return r;
                    } else {//如果邀请人不是本人，查看参团页面

                        //我要参团
                        Map map1 = new HashMap<String, Object>();
                        map1.put("userId", userId);
                        map1.put("activityId", activityId);
                        map1.put("collageOrder", leaderCollage.getCollageorder());//获取最新拼团的参团人员信息
                        List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

                        Map map2 = new HashMap<String, Object>();
                        map2.put("userId", userId);
                        map2.put("activityId", activityId);
                        map2.put("collageOrder", leaderCollage.getCollageorder());
                        int total = collageOrderService.queryTotal(map2);

                        //拼团结果
                        r.put("page", 2);//参团页
                        r.put("collage", leaderCollage);
                        r.put("partners", collageList);
                        r.put("total", total);
                        return r;
                    }
                }
            } else {//没有参加
                if (isNew) {//新人
                    if (new Date().compareTo(leaderCollage.getEndtime()) > 0) {//如果邀请人最新拼团已过期，进入结果页面
                        Map map1 = new HashMap<String, Object>();
                        map1.put("userId", userId);
                        map1.put("activityId", activityId);
                        map1.put("collageOrder", leaderCollage.getCollageorder());//获取最新拼团的参团人员信息
                        List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

                        Map map2 = new HashMap<String, Object>();
                        map2.put("userId", userId);
                        map2.put("activityId", activityId);
                        map2.put("collageOrder", leaderCollage.getCollageorder());
                        int total = collageOrderService.queryTotal(map2);

                        //拼团结果
                        r.put("page", 3);
                        r.put("collage", leaderCollage);
                        r.put("partners", collageList);
                        r.put("total", total);
                        return r;
                    } else {//如果邀请人最新拼团进行中，进入结果页面
                        //我要参团
                        Map map1 = new HashMap<String, Object>();
                        map1.put("userId", userId);
                        map1.put("activityId", activityId);
                        map1.put("collageOrder", leaderCollage.getCollageorder());//获取最新拼团的参团人员信息
                        List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；

                        Map map2 = new HashMap<String, Object>();
                        map2.put("userId", userId);
                        map2.put("activityId", activityId);
                        map2.put("collageOrder", leaderCollage.getCollageorder());
                        int total = collageOrderService.queryTotal(map2);

                        //拼团结果
                        r.put("page", 2);//参团页
                        r.put("collage", leaderCollage);
                        r.put("partners", collageList);
                        r.put("total", total);
                        return r;
                    }
                } else {//老人进邀请链接，只能开团
                    //我要开团
                    Map toCallageMap = new HashMap();
                    toCallageMap.put("activityId", activityId);
                    List<WfCollageActivityEntity> collageList = collageActivityService.queryList(toCallageMap);
                    WfCollageActivityEntity collageActivity = collageList.get(0);
                    r.put("page", 1);//开团页
                    r.put("collageActivity", collageActivity);
                    return r;
                }
            }
        }
    }


    /**
     * 拼团微信支付
     */
    @RequestMapping("/collagePay")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public R collagePay(HttpServletRequest req){

        int activityId =  Integer.valueOf(req.getParameter("activityId"));
        String userId =  req.getParameter("userId");
        int toUserId = ISsoLoginHelper.confirm(req);//参团人id
        String openId =  req.getParameter("openId");
        String page =  req.getParameter("page");
        boolean pageFlage =false;//开团
        if(page.equals("2")){
            pageFlage =true;//参团
        }

        WfCollageActivityEntity collage = collageActivityService.queryObject(activityId);

        //判断是否已参加拼团
        Map collageMap = new HashMap<String ,Object>();
        collageMap.put("toUserId",toUserId);
        collageMap.put("foreignId",collage.getForeignid());
        collageMap.put("type",collage.getType());
        //获取状态status not in(1,4) 的最新订单
        WfCollageOrderEntity collageOrder = collageOrderService.queryCollaging(collageMap);//获取团单状态；所买课程信息；参团最多人数；
        if(collageOrder!=null){
            return R.error(85,"此课程您已参加拼团，请勿重复购买！");
        }

        int access = -1;
        access =  checkCourse(toUserId, collage.getForeignid());
        if (access > 0) {
            return R.error(58, "此课程您已经购买！");
        }

        String orderCode = null;
        WfCollageOrderEntity  leaderCollage = null; //团长拼单
        if(pageFlage) {//参团
            //获取团长正在拼团的拼团单号
            Map map3 = new HashMap<String, Object>();
            map3.put("userId", userId);
            map3.put("activityId", activityId);
            //获取状态status  not in(1,4) 的最新订单
            leaderCollage = collageOrderService.queryLeaderCollaging(map3);
            orderCode = leaderCollage.getCollageorder();

            Map map2 = new HashMap<String, Object>();
            map2.put("userId", userId);
            map2.put("activityId", activityId);
            map2.put("collageOrder", orderCode);
            int total = collageOrderService.queryTotal(map2);
            if (total >= collage.getNum()) {
                return R.error(82, "拼团人员已满，请您主动发起或参与其他拼团！");
            }
        }else{//开团
            //拼团单号
            orderCode = DateUtil.getOrderCode();//根据当前时间生成拼团单号，yyMMddHHmmssSSS + 6随机数
        }

        BigDecimal actualPrice = null;
        R  result = new R();
        JSONObject res = null;
        if(!pageFlage) {//开团
            actualPrice = new BigDecimal(collage.getLeaderprice());
        }else{//参团
            actualPrice = new BigDecimal(collage.getCollageprice());
        }
        try {

            WfCollageOrderEntity collageOrderEntity = new WfCollageOrderEntity();
            collageOrderEntity.setActivityId(activityId);
            collageOrderEntity.setCollageorder(orderCode);
            collageOrderEntity.setCreatetime(new Date());
            collageOrderEntity.setTouserid(toUserId);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            //calendar.add(Calendar.HOUR, collage.getLongtime());//时
            calendar.add(Calendar.SECOND, collage.getLongtime());//秒

            if(pageFlage){//参团
                //获取团长的订单时间
                collageOrderEntity.setEndtime(leaderCollage.getEndtime());//设置拼团结束时间
                collageOrderEntity.setUserid(Integer.valueOf(userId));
            }else{//开团
                if(collage.getEndtime().compareTo(calendar.getTime())<0){//活动时间小于拼团过期时间
                    collageOrderEntity.setEndtime(collage.getEndtime());//设置活动时间
                }else {
                    collageOrderEntity.setEndtime(calendar.getTime());//设置拼团结束时间
                }
                collageOrderEntity.setUserid(toUserId);
            }
            collageOrderEntity.setForeignid(collage.getForeignid());
            collageOrderEntity.setType(collage.getType());
            collageOrderEntity.setStatus(1);//拼团单状态（1待付款|2已支付|3已完成|4已退款）
            collageOrderEntity.setSaleflag(0);//是否退单（1是 0否）
            collageOrderEntity.setVersion("3.0");
            collageOrderEntity.setWxpayorder("");
            collageOrderEntity.setRemark("");
            collageOrderService.save(collageOrderEntity);//保存待付款状态

            res = collageOrderService.dopay(req,orderCode+String.valueOf(toUserId),actualPrice,1,openId);
            result.putAll(res);
            result.put("orderNum", orderCode+String.valueOf(toUserId));
            return result;//返回json
        } catch (Exception e) {
            log.error("支付异常", e);
            if(e instanceof WFCMException){
                WFCMException ze = (WFCMException)e;
                result=R.error(ze.getErrCode(), ze.getMsg());
                return result;
            }else{
                return R.error();
            }
        }
    }

    //课程查重
    public int checkCourse(int uid, int courseId) {
        int access = -1;//标识
        //获取已购课程个数
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uid", uid);
        map.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
        List<WfGoodsOrderEntity> goodsOrderList = goodsOrderService.queryList(map);//根据uid获取订单
        for (int i = 0; i < goodsOrderList.size(); i++) {
            WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("orderCode", goodsOrderEntity.getOrdercode());
            map2.put("goodsSort", 1);//1.课程 2.章节3.vip卡 4商品
            List<WfGoodsOrderRelationEntity> courseList = goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程
            for (int j = 0; j < courseList.size(); j++) {
                if (courseId == courseList.get(j).getGoodsid()) {
                    access = 1;
                    break;//跳出课程循环
                }
            }
            if (access == 1) {
                break;//跳出订单循环
            }
            map2.put("goodsSort", 3);//1.课程 2.章节3.vip卡 4商品
            List<WfGoodsOrderRelationEntity> vipList = goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
            for (int m = 0; m < vipList.size(); m++) {
                Integer vcId = vipList.get(m).getGoodsid();
                Map<String, Object> map3 = new HashMap<String, Object>();
                map3.put("vipCardId", vcId);
                List<WfVipCardEntity> vipCardList = vipCardService.queryCourseList(map3);//获取课程包中个课程
                for (int k = 0; k < vipCardList.size(); k++) {
                    if (courseId == vipCardList.get(k).getCardCourseRelationList().get(0).getCourseInfoEntity().getId()) {
                        access = 1;
                        break;//若课程已买，则跳出课程包循环
                    }
                }
            }
            if (access == 1) {
                break;//跳出订单循环
            }
        }
        return access;//若access为-1,则说明此课程没买过；为1，则说明课程已买过
    }


    /**
     * 微信回调
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wechatreceive")
    @IgnoreSign
    @IgnoreToken
    @ResponseBody
    public void wechatreceive(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResponseHandler resHandler = new ResponseHandler(request, response);
        try {
            log.info("微信支付==进入==");
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            resHandler.setKey(ConstantUtil.GG_APP_KEY);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            response.setHeader("ContentType", "text/xml");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            outSteam.close();
            inStream.close();

            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            log.info("微信支付==result==" + result);
            Map<Object, Object> map = XMLUtil.doXMLParse(result);
            log.info("微信支付==map==" + map);

            String result_code = "";
            String out_trade_no = "";
            String trade_no = "";
            String total_fee ="";
            String time_end ="";
            for (Object keyValue : map.keySet()) {
                result_code = map.get("result_code").toString();//业务结果
                out_trade_no = map.get("out_trade_no").toString();//商户订单号
                trade_no = map.get("transaction_id").toString();//微信支付订单号
                total_fee = map.get("total_fee").toString();//总金额
                time_end = map.get("time_end").toString();//支付完成时间
            }

            WfCollageOrderEntity  collageOrder = (collageOrderService.queryByOrderCode(out_trade_no)).get(0);

            // 判断
            if(!WXPayUtil.isSignatureValid(result,ConstantUtil.GG_APP_KEY)){
                log.info("微信验签失败");
                resHandler.sendToCFT("FAIL");
            }
            if ("SUCCESS".equals(result_code) ) {
                //根据参团人数将拼团状态改为已完成
                collageOrder.setWxpayorder(trade_no);
                collageOrder.setStatus(2); //根据订单号将拼团状态改为已支付
                collageOrderService.update(collageOrder);

                Map map2 = new HashMap<String ,Object>();
                map2.put("userId",collageOrder.getUserid());
                map2.put("activityId",collageOrder.getActivityId());
                map2.put("collageOrder", collageOrder.getCollageorder());
                int total = collageOrderService.queryTotal(map2);
                WfCollageActivityEntity collage = collageActivityService.queryObject(collageOrder.getActivityId());
                //判断是否满员，若满员则拼单状态改为已完成//拼团单状态（1待付款|2已支付|3已完成|4已退款）
                if(total>=collage.getNum()){
                    Map map1 = new HashMap<String, Object>();
                    map1.put("userId",collageOrder.getUserid());
                    map1.put("activityId",collageOrder.getActivityId());
                    map1.put("collageOrder", collageOrder.getCollageorder());//获取最新拼团的参团人员信息
                    List<WfCollageOrderEntity> collageList = collageOrderService.queryPartners(map1);//获取参团人员信息；
                    for (int i = 0; i < collageList.size(); i++) {
                        WfCollageOrderEntity tmpCollageOrder = collageList.get(i);
                        tmpCollageOrder.setStatus(3);
                        collageOrderService.update(tmpCollageOrder);

                        //拼团单号
                        String orderCode = DateUtil.getOrderNum();//根据当前时间生成拼团单号，yyMMddHHmmssSSS + 0~1000000随机数

                        BigDecimal zero = BigDecimal.ZERO;
                        WfGoodsOrderEntity goodsOrderEntity = new WfGoodsOrderEntity();
                        goodsOrderEntity.setActivityinfo("拼团活动-原价"+collage.getOriginprice()+"元;拼团价"+collage.getCollageprice()+"元");
                        goodsOrderEntity.setNewcoppercash(zero);//消耗的新铜钱
                        goodsOrderEntity.setGold(zero);//消耗的金币
                        goodsOrderEntity.setNewGold(zero);//消耗的新金币
                        goodsOrderEntity.setCoppercash("0");//消耗的原铜钱
                        goodsOrderEntity.setGoodsamount(new BigDecimal(collage.getCollageprice()));//商品总金额
                        BigDecimal h = new BigDecimal("100");
                        goodsOrderEntity.setOrderamount(new BigDecimal(total_fee).divide(h,2,BigDecimal.ROUND_HALF_UP));//支付总金额
                        goodsOrderEntity.setOldcoppercash(zero);//老铜钱
                        goodsOrderEntity.setSpendcoin(zero);//订单花费铜钱数
                        goodsOrderEntity.setVersion("3.0");
                        goodsOrderEntity.setOrderstatus(4);//支付成功
                        goodsOrderEntity.setCouponsId(0);
                        goodsOrderEntity.setCouponsMemo("");
                        goodsOrderEntity.setOrdertime(new Date());
                        goodsOrderEntity.setPaytype(1);
                        goodsOrderEntity.setFreight(zero);
                        goodsOrderEntity.setUsersource("团购id-"+collage.getId());
                        goodsOrderEntity.setOrdercode(orderCode);
                        goodsOrderEntity.setUserid(tmpCollageOrder.getTouserid());
                        goodsOrderService.save(goodsOrderEntity);


                        WfGoodsOrderRelationEntity goodsOrderRelation = new WfGoodsOrderRelationEntity();
                        goodsOrderRelation.setGoodsprice((new BigDecimal(total_fee).divide(h,2,BigDecimal.ROUND_HALF_UP)));
                        goodsOrderRelation.setGoodsid(tmpCollageOrder.getForeignid());
                        goodsOrderRelation.setGoodssort(tmpCollageOrder.getType());
                        goodsOrderRelation.setNewcoppercash(zero);//新铜钱消耗
                        goodsOrderRelation.setGold(zero);//金币消耗
                        goodsOrderRelation.setNewGold(zero);//新金币消耗
                        goodsOrderRelation.setRealpay((new BigDecimal(total_fee).divide(h,2,BigDecimal.ROUND_HALF_UP)));//微信消费
                        goodsOrderRelation.setCouponscash(zero);
                        goodsOrderRelation.setActivitycash(zero);
                        goodsOrderRelation.setOldcoppercash(zero);
                        goodsOrderRelation.setBackflag(0);//是否退货
                        goodsOrderRelation.setOrdercode(orderCode);
                        goodsOrderRelation.setGoodscount(1);
                        goodsOrderRelation.setSaleflag(0);
                        goodsOrderRelation.setIsevaluate(2);//是否评价（1是2否）
                        goodsOrderRelation.setBackflag(0);//是否退货(0.否 1.是)
                        goodsOrderRelation.setCoppercash(zero);
                        goodsOrderRelation.setVersion("3.0");//版本号3.0
                        goodsOrderRelation.setUserid(tmpCollageOrder.getTouserid());
                        goodsOrderRelation.setCreatetime(new Date());
                        goodsOrderRelation.setOrderstatus(4);
                        goodsOrderRelation.setUserid(tmpCollageOrder.getTouserid());
                        goodsOrderRelationService.save(goodsOrderRelation);//保存
                    }
                    if(1==collageOrder.getType()) {
                        WfCourseInfoEntity courseInfo = courseInfoService.queryObject(collageOrder.getForeignid());
                        courseInfo.setCoursesalenumber(courseInfo.getCoursesalenumber()+collage.getNum());
                        courseInfoService.update(courseInfo);
                    }
                }

                log.info("微信支付，交易成功");
                resHandler.sendToCFT("SUCCESS");
            }else {
                log.info("微信支付失败");
                resHandler.sendToCFT("FAIL");
            }

        } catch (Exception e) {
            e.printStackTrace();
            try {
                resHandler.sendToCFT("FAIL");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }


    /**
     * 查询微信账单
     * @throws Exception
     */
    @RequestMapping(value = "doQuery")
    @IgnoreSign
    @IgnoreToken
    @ResponseBody
    public R doQuery(HttpServletRequest req) throws Exception {
        String orderNum = req.getParameter("orderNum");//拼团订单查询

        Map<String,String> map = new HashMap<String,String>();
        while(!("SUCCESS".equals(map.get("trade_state")))) {
            orderNum = req.getParameter("orderNum");//拼团购物订单查询
            List<WfCollageOrderEntity> collageOrderList = new ArrayList<WfCollageOrderEntity>();
            collageOrderList = collageOrderService.queryByOrderCode(orderNum);
            WfCollageOrderEntity collageOrder = collageOrderList.get(0);

            String appid = ConstantUtil.GG_APP_ID;
            // String appsecret = ConstantUtil.APP_SECRET;
            String partner = ConstantUtil.GG_PARTNER;
            String partnerkey = ConstantUtil.GG_PARTNER_KEY;

            WXOrderQuery query = new WXOrderQuery();
            query.setAppid(appid);//应用APPID
            query.setMch_id(partner);//商户号
            Random random = new Random();
            String randomStr = MD5Util.MD5Encode(String.valueOf(random.nextInt(1000000)), "utf-8").toUpperCase();
            System.out.println("randomStr="+randomStr);
            query.setNonce_str(MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase());//随机字符串
            query.setOut_trade_no(orderNum);//商户订单号
            query.setPartnerKey(partnerkey);//API秘钥
            //query.setTransaction_id(transactionId);//微信订单号(或商户订单号 二选一)
            query.setSign(createSign(query, partnerkey));//签名

            map = query.reqOrderquery();

            if("SUCCESS".equals(map.get("trade_state"))) {

                WfBillEntity b = billService.queryByOrderNum(orderNum);
                if(null == b) {
                    WfBillEntity bill = new WfBillEntity();
                    bill.setTradetime(map.get("time_end"));//支付完成时间
                    bill.setGhid(map.get("appid"));//app/公众号id
                    bill.setMchid(map.get("mch_id"));//商户号
                    bill.setSubmch("0");//子商户号
                    bill.setDeviceid(map.get("device_info"));//设备号
                    bill.setWxorder(map.get("transaction_id"));//微信支付订单号
                    bill.setBzorder(map.get("out_trade_no"));//商户订单号
                    bill.setOpenid(map.get("openid"));//用户标识
                    bill.setTradetype(map.get("trade_type"));//交易类型
                    bill.setTradestatus(map.get("trade_state"));//交易状态   SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 REVOKED—已撤销（刷卡支付） USERPAYING--用户支付中 PAYERROR--支付失败(其他原因，如银行返回失败)
                    bill.setBank(map.get("bank_type"));//付款银行
                    bill.setCurrency(map.get("fee_type"));//货币种类
                    bill.setTotalmoney(map.get("cash_fee"));//现金支付金额
                    bill.setRedpacketmoney(map.get("coupon_fee"));//代金券金额
                    bill.setOpenid(map.get("openid"));//代金券金额
                    bill.setWxrefund("0");//微信退款单号
                    bill.setBzrefund("0");//商户退款单号
                    bill.setRefundmoney("0.00");//退款金额openid
                    //bill.setRefundtype((String) map.get("time_end"));//退款类型
                    //bill.setRefundstatus((String) map.get("time_end"));//退款状态
                    String productname = "";
                    if("".equals(orderNum)) {//若购物订单号为空，则说明在操作充值
                        bill.setProductname("充值");
                    }else {
                        Map<String,Object> map1 =new  HashMap<String,Object>();
                        map1.put("orderCode", collageOrder.getCollageorder());

                        if(1 == collageOrder.getType()) {
                            WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(collageOrder.getForeignid());
                            productname = productname + courseInfo.getCoursename();
                        }else if(2 == collageOrder.getType()){
                            WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(collageOrder.getForeignid());
                            productname = productname + courseChapter.getChaptername();
                        }else if(3 == collageOrder.getType()){
                            WfVipCardEntity vipCard = vipCardService.queryObject(collageOrder.getForeignid());
                            productname = productname + vipCard.getCardname();
                        }
                        bill.setProductname(productname);//商品名称
                    }
                    bill.setBzdatapacket("");//商户数据包
                    double fee = Double.valueOf((String) map.get("cash_fee"))*0.006;
                    bill.setFee(String.valueOf(Math.round(fee*100000)/100000));
                    bill.setRate("0.6%");

                    billService.save(bill);
                }
                Map<String,Object> resultMap =new  HashMap<String,Object>();

                resultMap.put("totalPrice", Double.valueOf(map.get("cash_fee"))/100);//总金额
                return R.ok(resultMap);
            }else if("PAYERROR".equals(map.get("trade_state"))) {
                return R.error(57, "支付失败");
            }else if("ORDERPAID".equals(map.get("trade_state")) ) {
                log.info("商户订单已支付");
                return R.error(64, "订单已支付,请联系管理员");
            }else if("SIGNERROR".equals(map.get("trade_state")) ) {
                log.info("签名错误");
                return R.error(65, "签名错误");
            }else if("NOTPAY".equals(map.get("trade_state")) ) {
                log.info("订单未支付");
                return R.error(69, "订单未支付");
            }
    	/*else if("USERPAYING".equals(map.get("trade_state"))) {
    		return R.error(56, "订单支付中");
    	}*/
        }
        return R.error("交易失败，请联系管理员。");
    }



    /**
     * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     */
    public static String createSign(WXOrderQuery query, String AppKey) {
        SortedMap<String, String> nativeObj = new TreeMap<String, String>();
        nativeObj.put("appid", query.getAppid());
        nativeObj.put("mch_id", query.getMch_id());
        nativeObj.put("nonce_str", query.getNonce_str());
        nativeObj.put("out_trade_no", query.getOut_trade_no());
        //nativeObj.put("transaction_id", query.getTransaction_id());
        StringBuffer sb = new StringBuffer();
        Set es = nativeObj.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + AppKey);
        System.out.println("sb="+sb.toString());
        String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
        return sign;
    }



}
